﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace WpfBluetooth.ViewModel
{
    /// <summary>
    /// 
    /// </summary>
    public class BluetoothMode : ObservableObject
    {
        /// <summary>
        /// 蓝牙信息
        /// </summary>
        public BluetoothDeviceInfo bluetoothDeviceInfo { get; set; }
        /// <summary>
        /// 蓝牙客户端
        /// </summary>
        public BluetoothClient client { get; set; }
        /// <summary>
        /// 名称
        /// </summary>
        private string _name;
        /// <summary>
        /// 名称
        /// </summary>
        public string name { get => _name; set => SetProperty(ref _name, value); }
        /// <summary>
        /// 蓝牙服务
        /// </summary>
        private ObservableCollection<BluetoothServer> _bluetoothServer;
        /// <summary>
        /// 蓝牙服务
        /// </summary>
        public ObservableCollection<BluetoothServer> bluetoothServer { get => _bluetoothServer; set => SetProperty(ref _bluetoothServer, value); }

        /// <summary>
        /// 连接
        /// </summary>
        public ICommand Link { get; set; }
        /// <summary>
        /// 配队
        /// </summary>
        public ICommand pair { get; set; }

        public BluetoothMode()
        {
            bluetoothServer=new ();
            Link = new AsyncRelayCommand(LinkMethod);
            pair = new RelayCommand(pairMethod);

            
        }
        /// <summary>
        /// 配队
        /// </summary>
        private void pairMethod()
        {
            if (!bluetoothDeviceInfo.Authenticated)
            {
                var dst = BluetoothSecurity.PairRequest(bluetoothDeviceInfo.DeviceAddress);
                if (dst)
                {
                    Console.WriteLine("配对成功");
                }
                else
                {

                    Console.WriteLine("配对失败");
                }
            }

        }

        private async Task LinkMethod()
        {

            bluetoothServer.Clear();
            var dst = await bluetoothDeviceInfo.GetRfcommServicesAsync(false);

            foreach (var item in dst)
            {
                var bs = new BluetoothServer()
                {
                    sever = item,
                    bluetoothDeviceInfo = bluetoothDeviceInfo,
                    blueName = BluetoothService.GetName(item)
                };
                if(string.IsNullOrEmpty(bs.blueName))
                {
                    bs.blueName = item.ToString();
                }
                bluetoothServer.Add(bs);
             
            }
        }
    }
}
